<!-- src/views/accounts/Accounts.vue -->
<template>
    <div class="accounts-page">
      <!-- 视图 & 时间粒度切换 -->
      <div class="controls">
        <el-radio-group v-model="viewType" size="small">
          <el-radio-button label="personal">👤 个人</el-radio-button>
          <el-radio-button label="family">👨‍👩‍👧 家庭</el-radio-button>
        </el-radio-group>
  
        <el-radio-group v-model="timeGranularity" size="small" style="margin-left: 16px">
          <el-radio-button label="monthly">📅 月度</el-radio-button>
          <el-radio-button label="yearly">📆 年度</el-radio-button>
        </el-radio-group>
      </div>
  
      <!-- 图表区域 -->
      <div class="charts-grid">
        <!-- 收支趋势图 -->
        <ChartCard
          :title="`${currentViewLabel}${currentGranularityLabel}收支趋势`"
          :option="trendChartOption"
          height="400px"
          @chart-click="handleTrendClick"
        />
  
        <!-- 收支类型占比图 -->
        <ChartCard
          :title="`${currentViewLabel}${currentGranularityLabel}收支类型占比`"
          :option="pieChartOption"
          height="400px"
          @chart-click="handlePieClick"
        />
      </div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed } from 'vue'
  import * as echarts from 'echarts'
  import ChartCard from '@/components/common/ChartCard.vue'
  import { AccountApi, AccountCategoryStat ,TrendDataItem} from '@/api/family/account'
  import { onMounted } from 'vue';



  // 存储从后端获取的数据
  const financialData = ref<FinancialData | null>(null)

  // ========== 静态模拟数据 ==========
  interface FinancialData {
    income: Record<string, number> // 如 { '工资': 8000, '奖金': 2000 }
    expense: Record<string, number> // 如 { '餐饮': 1500, '交通': 500 }
    timeline: {
      labels: string[] // 如 ['1月', '2月', ...] 或 ['2023', '2024']
      income: number[]
      expense: number[]
    }
  }
  // 👤 个人 - 月度数据 (从后端获取)  // ========== 核心逻辑 ==========
  const fetchPersonalMonthlyData = async (): Promise<FinancialData> => {
    try {
      const now = new Date();
      const endDate = now.toISOString().split('T')[0];
      const startDate = new Date(now.getFullYear(), now.getMonth() - 11, 1).toISOString().split('T')[0];
      
      // console.log("时间参数:",endDate, startDate);
      // const params: AccountQuery = {
      //   user_id: userStore.id, 
      //   page: 1,
      //   page_size: 10,
      //   start_datetime: startDate,
      //   end_datetime: endDate,
      //   months: 12
      // };
      // 为不同的 API 准备各自需要的参数
      
      // 获取统计数据 (statistics) 需要 start_datetime, end_datetime
      // / 后端改成datetime了。
      const statsParams = {
        start_datetime: startDate,
        end_datetime: endDate
      };

      const [statisticsRes, incomeStatsRes, expenseStatsRes, trendRes] = await Promise.all([
        AccountApi.getAccountStatistics(statsParams),
        AccountApi.getAccountCategoryStats({...statsParams,type_: 'income'}),
        AccountApi.getAccountCategoryStats({...statsParams,type_: 'expense'}),
        AccountApi.getAccountTrend({months: 12})
      ]);
      console.log("获取个人统计数据结果:",statisticsRes, incomeStatsRes, expenseStatsRes, trendRes);
      // 处理收入分类统计
      const incomeStats = incomeStatsRes.data || [];
      const incomeData: Record<string, number> = {};
      incomeStats.forEach((item: AccountCategoryStat) => {
        incomeData[item.category] = parseFloat(item.amount);
      });

      // 处理支出分类统计
      const expenseStats = expenseStatsRes.data || [];
      const expenseData: Record<string, number> = {};
      expenseStats.forEach((item: AccountCategoryStat) => {
        expenseData[item.category] = parseFloat(item.amount);
      });

    // 处理月度趋势数据 (假设 data 是一个数组)
    const trendDataArray: TrendDataItem[] = trendRes.data; // 明确类型

    const monthLabels = trendDataArray.map(item => item.month); // 提取所有 month 值
    const monthlyIncome = trendDataArray.map(item => item.income); // 提取所有 income 值
    const monthlyExpense = trendDataArray.map(item => item.expense); // 提取所有 expense 值

      return {
        income: incomeData,
        expense: expenseData,
        timeline: {
          labels: monthLabels,
          income: monthlyIncome,
          expense: monthlyExpense
        }
      };
    } catch (error) {
      console.error("获取个人月度数据失败:", error);
      throw error;
    }
  };
    
  // // 👤 个人 - 月度数据 （静态示例）
  // const personalMonthlyData: FinancialData = {
  //   income: {
  //     '工资': 8000,
  //     '奖金': 2000,
  //     '理财收益': 500
  //   },
  //   expense: {
  //     '餐饮': 1500,
  //     '交通': 500,
  //     '购物': 1000,
  //     '房贷': 3000,
  //     '娱乐': 800
  //   },
  //   timeline: {
  //     labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  //     income: [8500, 8000, 8500, 10000, 8000, 8500, 8000, 8500, 10000, 8000, 8500, 15000],
  //     expense: [5800, 6000, 5500, 6200, 5800, 6000, 5500, 6200, 5800, 6000, 5500, 7000]
  //   }
  // }
  

  // 👤 个人 - 年度数据
  const personalYearlyData: FinancialData = {
    income: {
      '工资': 96000,
      '奖金': 24000,
      '理财收益': 6000
    },
    expense: {
      '餐饮': 18000,
      '交通': 6000,
      '购物': 12000,
      '房贷': 36000,
      '娱乐': 9600
    },
    timeline: {
      labels: ['2021', '2022', '2023', '2024'],
      income: [100000, 110000, 120000, 130000],
      expense: [70000, 75000, 80000, 85000]
    }
  }
  

  // 👨‍👩‍👧 家庭 - 月度数据
  const familyMonthlyData: FinancialData = {
    income: {
      '工资': 15000,
      '奖金': 5000,
      '理财收益': 2000,
      '房租收入': 3000
    },
    expense: {
      '餐饮': 3000,
      '交通': 1500,
      '购物': 2500,
      '房贷': 5000,
      '教育': 2000,
      '医疗': 1000
    },
    timeline: {
      labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      income: [20000, 18000, 22000, 25000, 20000, 22000, 20000, 22000, 25000, 20000, 22000, 30000],
      expense: [12000, 13000, 11000, 14000, 12000, 13000, 11000, 14000, 12000, 13000, 11000, 16000]
    }
  }
  
  // 👨‍👩‍👧 家庭 - 年度数据
  const familyYearlyData: FinancialData = {
    income: {
      '工资': 180000,
      '奖金': 60000,
      '理财收益': 24000,
      '房租收入': 36000
    },
    expense: {
      '餐饮': 36000,
      '交通': 18000,
      '购物': 30000,
      '房贷': 60000,
      '教育': 24000,
      '医疗': 12000
    },
    timeline: {
      labels: ['2021', '2022', '2023', '2024'],
      income: [220000, 240000, 260000, 280000],
      expense: [150000, 160000, 170000, 180000]
    }
  }
  

  // ========== 响应式状态 ==========
  const viewType = ref<'personal' | 'family'>('personal')
  const timeGranularity = ref<'monthly' | 'yearly'>('monthly')
  
  // 计算当前应显示的数据
  const currentData = computed<FinancialData>(() => {
    // 优先使用从后端获取的数据
    if (financialData.value) {
      if (viewType.value === 'personal') {
        return timeGranularity.value === 'monthly' ? financialData.value : personalYearlyData;
      } else {
        return timeGranularity.value === 'monthly' ? familyMonthlyData : familyYearlyData;
      }
    }
    
    // 如果没有获取到数据，则使用静态数据
    // 这里修正了原始逻辑，使其更符合预期
    if (viewType.value === 'personal') {
      // 注意：原始代码中 personalMonthlyData 是函数，这里假设你有静态的 personalMonthlyData 对象
      // 如果没有，可以暂时用 yearly 的或者返回一个默认对象
      return timeGranularity.value === 'monthly' ? personalYearlyData : personalYearlyData; 
    } else {
      return timeGranularity.value === 'monthly' ? familyMonthlyData : familyYearlyData;
    }
  });
  
  const currentViewLabel = computed(() => viewType.value === 'personal' ? '个人' : '家庭')
  const currentGranularityLabel = computed(() => timeGranularity.value === 'monthly' ? '月度' : '年度')
  
  // ========== 图表配置 ==========
  // 折线图配置
  const trendChartOption = computed<echarts.EChartsOption>(() => ({
    tooltip: { trigger: 'axis' },
    legend: { data: ['收入', '支出'] },
    grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: currentData.value.timeline.labels
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '收入',
        type: 'line',
        data: currentData.value.timeline.income,
        smooth: true,
        lineStyle: { color: '#673AB7' },
        itemStyle: { color: '#673AB7' }
      },
      {
        name: '支出',
        type: 'line',
        data: currentData.value.timeline.expense,
        smooth: true,
        lineStyle: { color: '#4ECDC4' },
        itemStyle: { color: '#4ECDC4' }
      }
    ]
  }))
  
  // 饼图配置
  const pieChartOption = computed<echarts.EChartsOption>(() => {
    const { income, expense } = currentData.value
  
    // 合并收入和支出数据，用不同颜色区分
    const pieData = [
      ...Object.entries(income).map(([name, value]) => ({
        name: `收入 - ${name}`,
        value,
        itemStyle: { color: '#673AB7' }
      })),
      ...Object.entries(expense).map(([name, value]) => ({
        name: `支出 - ${name}`,
        value,
        itemStyle: { color: '#4ECDC4' }
      }))
    ]
  
    return {
      tooltip: { trigger: 'item' },
      legend: { orient: 'vertical', left: 'left' },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
  })
  
  // ========== 事件处理 ==========
  const handleTrendClick = (params: any) => {
    console.log('趋势图点击:', params)
  }
  
  const handlePieClick = (params: any) => {
    console.log('饼图点击:', params)
  }

  // ========== 生命周期 ==========
  onMounted(async () => {
    try {
      // 页面加载时自动调用并存储数据
      financialData.value = await fetchPersonalMonthlyData();
      console.log("数据加载成功:", financialData.value);
    } catch (error) {
      console.error("页面加载时获取数据失败:", error);
      // 可以在这里设置默认数据或显示错误提示
    }
  });

  </script>
  
  <style scoped>
  .accounts-page {
    padding: 20px;
  }
  
  .controls {
    margin-bottom: 24px;
    display: flex;
    align-items: center;
  }
  
  .charts-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
  }
  
  /* 响应式：小屏幕堆叠 */
  @media (max-width: 768px) {
    .charts-grid {
      grid-template-columns: 1fr;
    }
  }
  </style>